package controllers

import "gitee.com/wayjin/fabricsdk-go/caclient"

type CryptoCert struct {
	cacert    []byte
	signcert  []byte
	key       []byte
	tlscacert []byte
	servercrt []byte
	serverkey []byte
}

func getFabricCertificate(name, secret, hostname string, typ caclient.IdentityType) (*CryptoCert, error) {
	cryptoCert := &CryptoCert{}
	mspKeyStore, err := getMSPFromCA(name, secret, hostname, typ)
	if err != nil {
		return nil, err
	}
	tlsKeyStore, err := getTLSFromCA(name, secret, hostname, typ)
	if err != nil {
		return nil, err
	}
	cryptoCert.cacert = mspKeyStore.GetRootCert()
	cryptoCert.signcert = mspKeyStore.GetSignCert()
	cryptoCert.key, err = mspKeyStore.GetRawKey(nil)
	if err != nil {
		return nil, err
	}
	cryptoCert.tlscacert = tlsKeyStore.GetRootCert()
	cryptoCert.servercrt = tlsKeyStore.GetSignCert()
	cryptoCert.serverkey, err = tlsKeyStore.GetRawKey(nil)
	if err != nil {
		return nil, err
	}
	return cryptoCert, nil
}

func getMSPFromCA(name, secret, hostname string, typ caclient.IdentityType) (caclient.KeyStore, error) {
	client, err := caclient.NewClientWithURL("http://admin:adminpw@localhost:32090")
	if err != nil {
		return nil, err
	}
	req := caclient.NewRegisterRequest(name, secret, typ)
	err = client.Register(req, nil)
	if err != nil {
		if !caclient.ErrIsRegistered(err) {
			return nil, err
		}
	}

	enrollReq := caclient.EnrollmentRequest{Name: name, Secret: secret, Hosts: []string{hostname}}
	return client.Enroll(enrollReq)
}

func getTLSFromCA(name, secret, hostname string, typ caclient.IdentityType) (caclient.KeyStore, error) {
	client, err := caclient.NewClientWithURL("http://admin:adminpw@localhost:31149")
	if err != nil {
		return nil, err
	}
	req := caclient.NewRegisterRequest(name, secret, typ)
	req.Profile = "tls"
	err = client.Register(req, nil)
	if err != nil {
		if !caclient.ErrIsRegistered(err) {
			return nil, err
		}
	}

	enrollReq := caclient.EnrollmentRequest{Name: name, Secret: secret, Profile: "tls", Hosts: []string{hostname}}
	return client.Enroll(enrollReq)
}

var mspConfig = `NodeOUs:
  Enable: true
  ClientOUIdentifier:
    Certificate: cacerts/cacert.pem
    OrganizationalUnitIdentifier: client
  PeerOUIdentifier:
    Certificate: cacerts/cacert.pem
    OrganizationalUnitIdentifier: peer
  AdminOUIdentifier:
    Certificate: cacerts/cacert.pem
    OrganizationalUnitIdentifier: admin
  OrdererOUIdentifier:
    Certificate: cacerts/cacert.pem
    OrganizationalUnitIdentifier: orderer`
